package com.mck.service.impl;

import com.mck.anno.OperationLog;
import com.mck.entity.FileInfo;
import com.mck.entity.uploadFile;
import com.mck.entity.User;
import com.mck.mapper.FileMapper;
import com.mck.mapper.UserMapper;
import com.mck.service.UploadFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class UploadFileServiceImpl implements UploadFileService {

    @Autowired
    private UserMapper userMapper;

    // 获取yml文件的上传文件路径
    @Value("${spring.servlet.multipart.location}")
    private String uploadDir;

    @Autowired
    private FileMapper fileMapper;

    // 上传文件
    @OperationLog
    @Override
    @Transactional
    public void uploadFile(uploadFile file) {
        MultipartFile multipartFile = file.getFile();

        // 校验文件是否为空
        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        // 构建文件名和路径
        String fileType = file.getFileType();
        Integer userId = file.getUserId();
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = fileType + "_" + userId + "_" + originalFilename;
        String filePath = uploadDir + java.io.File.separator + fileName;

        // 创建目标文件
        java.io.File dest = new java.io.File(filePath);
        try {
            // 获取父目录
            java.io.File parentDir = dest.getParentFile();

            // 确保目录存在
            if (parentDir != null && !parentDir.exists()) {
                // 创建目录并检查结果
                if (!parentDir.mkdirs()) {
                    throw new IOException("无法创建目录: " + parentDir.getAbsolutePath());
                }
            }

            // 存入数据库
            FileInfo fileInfo = new FileInfo();
            fileInfo.setFileName(fileName);
            fileInfo.setFilePath(filePath);
            fileInfo.setFileType(fileType);
            fileInfo.setUserId(userId);
            fileInfo.setUploadTime(LocalDateTime.now());
            fileMapper.uploadFile(fileInfo);

            // 如果是上传头像，则更新用户信息
            if ("avatar".equals(fileType)) {
                User user = new User();
                user.setAvatarId(fileInfo.getId());
                user.setUserId(userId);
                userMapper.updateUserAvatar(user);
            }

            // 保存文件
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException("文件保存失败: " + e.getMessage(), e);
        }
    }

    // 获取文件列表
    @Override
    @Cacheable(value = "files", key = "'all'", unless = "#result.isEmpty()")
    public List<FileInfo> getFileList() {
        return fileMapper.getFileList();
    }

    // 获取指定文件
    @Override
    @Cacheable(value = "files", key = "#fileInfo.fileType + '_' + #fileInfo.id", unless = "#result.isEmpty()")
    public List<FileInfo> getFileSpecific(FileInfo fileInfo) {
        return fileMapper.getFileSpecific(fileInfo);
    }

    // 删除文件
    @OperationLog
    @Override
    @CacheEvict(value = "files", allEntries = true)
    public void deleteFile(List<Integer> id) {
        for (Integer i : id) {
            FileInfo fileInfo = new FileInfo();
            fileInfo.setId(i);
            fileMapper.deleteFile(fileInfo);
        }
    }

}
